import Vue from 'vue';
import axios from 'axios';
import { Message } from 'element-ui';
import router from '@/router';

const defaultOptions = {
  // withCredentials: true,
  timeout: 30000,
};

axios.interceptors.request.use((config) => {
  let token = localStorage.getItem('TOKEN');
  if (token) {
    config.headers['X-Token'] = token;
  }
  return config;
});

axios.interceptors.response.use(
  (response) => {
    // console.log(response);
    if (response.status === 200) {
      const { data } = response;
      if (data.code === 200) {
        return data.data;
      } else if (data.code === 401) {
        localStorage.removeItem('TOKEN');
        router.replace('/');
        Message.error(data.msg);
        return {};
      } else {
        Message.error(data.msg);
        return {};
      }
    }
  },
  (error) => {
    console.log('Request error');
    return Promise.resolve(error.response);
  },
);

export default {
  get: (url, data, options = {}) => {
    return new Promise((resolve) => {
      axios(url, {
        method: 'get',
        params: data || {},
        ...defaultOptions,
        ...options,
      }).then((res) => {
        resolve(res);
      });
    });
  },
  post: (url, data, options = {}) => {
    return new Promise((resolve) => {
      axios(url, {
        method: 'post',
        data: data || {},
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
        },
        ...defaultOptions,
        ...options,
      }).then((res) => {
        resolve(res);
      });
    });
  },
};
